package xyz.csmcool.imchat.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import xyz.csmcool.imchat.entity.PrivateChats;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import xyz.csmcool.imchat.entity.RoomsChats;
import xyz.csmcool.imutil.dto.LastMessageDto;
import xyz.csmcool.imutil.dto.LastPrivateMessageDto;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author csmcool
 * @since 2022-08-24
 */
@Mapper
public interface PrivateChatsMapper extends BaseMapper<PrivateChats> {

    /**
     * 翻页查看历史记录
     * @param page
     * @param limit
     * @param sid
     * @param fid
     * @param id
     * @return
     */
    @Select("SELECT * FROM (SELECT * FROM `sjim_private_chats` " +
            "WHERE (receive_id = #{sid} AND sender_id = #{fid}) OR (sender_id = #{sid} AND receive_id = #{fid}) " +
            "" +
            "ORDER BY id DESC LIMIT #{page},#{limit}) a ORDER BY a.id")
    List<PrivateChats> selectHistoryChat(@Param("page") Long page, @Param("limit") Long limit,
                                       @Param("sid") Integer sid, @Param("fid") Integer fid,
                                       @Param("id") Integer id);

    /**
     * 查询总数
     * @param sid
     * @param fid
     * @return
     */
    @Select("SELECT COUNT(*) FROM `sjim_private_chats` " +
            "WHERE (receive_id = #{sid} AND sender_id = #{fid}) OR (sender_id = #{sid} AND receive_id = #{fid})")
    Integer selectCount(@Param("sid") Integer sid, @Param("fid") Integer fid);

    /**
     * 获取私聊的最后一条消息
     * @param ids
     * @param uid *
     * @return
     */
    @Select("<script>" +
            "SELECT rid,sid,message FROM ( SELECT receive_id rid,sender_id sid,message,create_time FROM `sjim_private_chats` " +
            "force index(index_receive_id,index_sender_id,index_id) " +
            "WHERE (sender_id = #{uid} AND receive_id " +
            "<if test='ids.size() > 0' >" +
            "IN" +
            "</if>" +
            "<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')' >" +
            "#{item}" +
            "</foreach>" +
            " )" +
            " OR (sender_id IN" +
            "<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')' >" +
            "#{item}" +
            "</foreach>" +
            " AND receive_id = #{uid})" +
            " ORDER BY create_time DESC) a GROUP BY rid,sid ORDER BY create_time DESC" +
            "</script>")
    List<LastPrivateMessageDto> getLastPrivateMessage(@Param("ids") List<Integer> ids, @Param("uid") Integer uid);
}
